﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Cool.Core.ComDto;
using Cool.Core.Entities.System;
using Cool.Core.Enums;
using Cool.Core.Managers;
using Furion;
using Furion.DependencyInjection;

namespace Cool.Core.DataExtensions
{
    /// <summary>
    /// 部门过滤扩展
    /// </summary>
    [SkipScan]
    public static class DeptQueryableExtensions
    {
        public static IQueryable<TEntity> ToDeptPermsList<TEntity>(
            this IQueryable<TEntity> entities)
            where TEntity : DeptBaseDto
        {
            var  userManager= App.GetService<IUserManager>();

            Expression<Func<TEntity, bool>> expression = null;
            foreach (var role in userManager.Roles)
            {
                char dataScope = role.DataScope;

                //全部数据权限
                if (dataScope == ((int)DeptDataScope.DATA_SCOPE_ALL).ToString().ToCharArray()[0])
                {
                    continue;
                }

                //自定义部门权限
                if (dataScope == ((int)DeptDataScope.DATA_SCOPE_CUSTOM).ToString().ToCharArray()[0])
                {
                    var deptIds = userManager.GetDeptCustomsByRoles();
                    expression = expression.Compose(p => deptIds.Contains(p.DeptId), Expression.Or);
                }

                //本部门权限
                if (dataScope == ((int)DeptDataScope.DATA_SCOPE_DEPT).ToString().ToCharArray()[0])
                {
                    expression = expression.Compose(p => p.DeptId == userManager.User.DeptId, Expression.Or);
                }

                //TODO:本部门及以下数据权限待完善

                //只查看自己数据权限
                if (dataScope == ((int)DeptDataScope.DATA_SCOPE_SELF).ToString().ToCharArray()[0])
                {
                    expression = expression.Compose(p => p.UserId == userManager.UserId, Expression.Or);
                }
            }
            return expression==null ? entities : entities.Where(expression);
        }

        public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
        {
            if (first == null) return second;
            // build parameter map (from parameters of second to parameters of first)
            var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f);

            // replace parameters in the second lambda expression with parameters from the first
            var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);
            // apply composition of lambda expression bodies to parameters from the first expression 
            return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
        }
    }

    public class ParameterRebinder : ExpressionVisitor
    {
        private readonly Dictionary<ParameterExpression, ParameterExpression> map;
        public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
        {
            this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
        }

        public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
        {
            return new ParameterRebinder(map).Visit(exp);
        }
        protected override Expression VisitParameter(ParameterExpression p)
        {
            ParameterExpression replacement;
            if (map.TryGetValue(p, out replacement))
            {
                p = replacement;
            }
            return base.VisitParameter(p);
        }

    }
}
